<template>
	<view class="form pdd32">
		<up-form
			:labelStyle="{
				fontFamily: 'SourceHanSansTC, SourceHanSansTC',
				fontWeight: '400',
				fontSize: '28rpx',
				color: '#888888',
				lineHeight: '40rpx',
				textAlign: 'left',
				fontStyle: 'normal',
				marginRight: '32rpx'
			}"
			:model="formData"
			ref="uForm"
			labelWidth="auto"
			errorType="message"
		>
			<up-form-item
				:customStyle="{ padding: item.type === 'slot' ? '0' : '20rpx 0' }"
				:borderBottom="index != formList.length - 1"
				:labelPosition="['textarea', 'upload'].includes(item.type) ? 'top' : 'left'"
				v-for="(item, index) in formList"
				:key="item.prop"
				v-bind="item"
			>
				<template v-if="item.type === 'slot'">
					<slot :name="item.prop"></slot>
				</template>
				<template v-if="item.type === 'image'">
					<view class="" style="display: flex; justify-content: flex-end" @click="() => getPortraitUrl(item)">
						<image
							:src="formData[item.prop] || config.getImage('iconDefault')"
							style="width: 128rpx; height: 128rpx; margin-right: 8rpx; border-radius: 50%"
							mode=""
						></image>
					</view>
				</template>
				<template v-if="['text', 'password'].includes(item.type)">
					<!-- 输入框 || 密码框-->
					<up-input
						disabledColor="#ffffff"
						inputAlign="right"
						border="none"
						v-model="formData[item.prop]"
						v-bind="item"
						:maxlength="['realEstateNum'].includes(item.prop) ? 40 : 18"
					></up-input>
				</template>
				<template v-if="item.type == 'textarea'">
					<!-- 文本域 -->
					<up-textarea
						:customStyle="{ padding: '18rpx 0', backgroundColor: '#ffffff' }"
						border="none"
						v-model="formData[item.prop]"
						v-bind="item"
						maxlength="200"
					></up-textarea>
				</template>
				<template v-if="item.type == 'popup'">
					<!-- 选择框 -->
					<view :style="{ height: '100%', width: '100%' }" @click="() => changePopupShow(item)">
						<view class="" style="display: flex;justify-content: flex-end;align-items: center;" v-if="item.code == 'country'">
							<image style="width: 48rpx; height: 48rpx; border-radius: 50%;margin-right: 32rpx;" v-if="item.columns.find((i) => i.id == formData[item.prop])" :src="item.columns.find((i) => i.id == formData[item.prop]).countryUrl" mode=""></image>
							<view class="kuang" :class="item.columns.find((i) => i.id == formData[item.prop]) ? 'you' : 'wu'">
								{{ item.columns.find((i) => i.id == formData[item.prop])?.countryName || item.placeholder }}
							</view>
						</view>
						<view class="kuang" :class="item.columns.find((i) => i.value == formData[item.prop]) ? 'you' : 'wu'" v-else>
							{{ item.columns.find((i) => i.value == formData[item.prop])?.name || item.placeholder }}
						</view>
					</view>
				</template>
				<template v-if="item.type == 'picker'">
					<!-- 选择所属地区 -->
					<view :style="{ height: '100%', width: '100%' }" @click="() => changePickerShow(item)">
						<up-input
							inputAlign="right"
							:style="{ pointerEvents: 'none', height: '100%', width: '100%' }"
							v-model="formData[item.prop]"
							v-bind="item"
							disabled
							border="none"
							disabledColor="#ffffff"
						>
							<template #suffix>
								<up-icon size="32rpx" :name="config.getImage('right')"></up-icon>
							</template>
						</up-input>
					</view>
				</template>
				<template v-if="item.type == 'datetime'">
					<!-- 选择时间 -->
					<view :style="{ height: '100%', width: '100%' }" @click="() => changeDatetimeShow(item)">
						<up-input
							inputAlign="right"
							:style="{ pointerEvents: 'none', height: '100%', width: '100%' }"
							v-model="formData[item.prop]"
							v-bind="item"
							disabled
							border="none"
							disabledColor="#ffffff"
						>
							<template #suffix>
								<up-icon size="32rpx" :name="config.getImage('time')"></up-icon>
							</template>
						</up-input>
					</view>
				</template>
				<template v-if="item.type == 'upload'">
					<!-- 上传文件 -->
					<view class="shangchaun">
						<view class="tu" v-for="(i, index) in fileList" :key="i.url">
							<view
								class="imgDa"
								:style="`background:url(${config.getImage(uploadIcon[i.name.split('.').pop()] || 'pdf')})  no-repeat center / 100% 100%`"
								@click="() => fileCilck(i.url)"
							></view>
							<view class="cen" @click="() => fileCilck(i.url)">
								<view class="name font28">{{ i.name }}</view>
								<view class="daXiao font28">{{ (i.size / 1024 / 1024).toFixed(2) }}MB</view>
							</view>
							<view
								class="img"
								:style="{
									background: `url(${config.getImage('deleteFile')}) no-repeat center / 100% 100%`
								}"
								@click="() => deleteFileClick(item, i, index)"
							></view>
						</view>
						<view class="fileAdd">
							<!-- <up-icon size="132rpx" :name="config.getImage('addFile')" @click="() => clickShangChuan(item)"></up-icon> -->
							<up-icon size="132rpx" :name="config.getImage('addFile')" @click="() => clickShangChuan(item)"></up-icon>
							<view class="right">
								<view class="font28">支持.Word .Excel .PDF格式文件上传</view>
								<view class="font28">最大支持20MB文件</view>
							</view>
						</view>
					</view>
				</template>
				<template v-if="item.type == 'textarea' && item.label && item.label.includes('址')" #right>
					<up-icon :customStyle="{ marginTop: '-216rpx' }" size="32rpx" :name="config.getImage('address')"></up-icon>
				</template>
				<template v-if="['image', 'popup'].includes(item.type)" #right>
					<up-icon size="32rpx" :name="config.getImage('right')"></up-icon>
				</template>
			</up-form-item>
		</up-form>

		<up-datetime-picker
			ref="datetimePickerRef"
			v-if="isDatetime"
			:show="datetimeShow"
			closeOnClickOverlay
			@confirm="datetimeConfirm"
			@cancel="datetimeClose"
			@close="datetimeClose"
			:minDate="
				dataTimeList.includes(datetimeObj.label)
					? dayjs().subtract(100, 'year').valueOf()
					: dayjs().subtract(10, 'year').valueOf()
			"
			:maxDate="dataTimeList.includes(datetimeObj.label) ? dayjs().add(100, 'year').valueOf() : dayjs().valueOf()"
			:formatter="formatter"
			v-bind="datetimeObj"
			v-model="formData[datetimeObj.prop]"
		></up-datetime-picker>
	</view>
	<up-popup v-if="isPicker" :show="pickerShow" round="24rpx" @close="()=>diZhiUp(false)">
		<view class="diZhi">
			<view class="top flex_center">
				<view class="zhanwei"></view>
				<view class="titt font28">所属地区</view>
				<view class="zhanwei"></view>
				<up-icon size="48rpx" :name="config.getImage('closeUp')" @click="()=>diZhiUp(false)"></up-icon>
			</view>
			<view class="dizhiItem">
				<view class="xuanZe font28" v-for="(item,index) in diZhiItem" :key="item" @click="()=>clickTiShi(item,index)">{{ item }}</view>
				<view class="tiShi font28" v-if="tiShi">{{ tiShi }}</view>
			</view>
			<view class="con">
				<view class="con_item font28" v-for="item in diZhiList" :key="item" @click="() => diZhiItemClick(item)">
					{{ item.areaName }}
				</view>
			</view>
		</view>
	</up-popup>
	<up-popup v-if="isPopup" :show="popupShow" round="24rpx" @close="popupShow = false">
		<view style="max-height: 70vh; overflow: auto">
			<view class="popup" :class="{ isPopup: item.value == popupITem.value }" @click="() => enter(item)" v-for="(item, index) in popup.columns" :key="item.name">
				<view class="text">{{ item.name }}</view>
			</view>
		</view>
		<view class="btn">
			<view class="off" @click="popupShow = false">取消</view>
		</view>
	</up-popup>
	<up-popup v-if="isShangChaun" :show="shangChuanShow" round="24rpx" @close="shangChuanShow = false">
		<view class="popup" :class="{ isPopup: item.value == ShangChuanItem.value }" @click="() => enterShangChuan(item)" v-for="(item, index) in uploadList" :key="item.name">
			<view class="text">{{ item.name }}</view>
		</view>
		<view class="btn">
			<view class="off" @click="shangChuanShow = false">取消</view>
		</view>
	</up-popup>
	<up-modal
		v-if="isShangChaun"
		:show="deleteShow"
		@cancel="deleteShow = false"
		showCancelButton
		:closeOnClickOverlay="true"
		confirmColor="#FF4646"
		@confirm="confirm"
		@close="deleteShow = false"
		title="确认删除上传的附件吗？"
	>
		<view style="text-align: center; color: #888888">
			删除后无法找回哦!
			<br />
			请谨慎!!!
		</view>
	</up-modal>
	<up-toast ref="toast"></up-toast>
	<Dictionary v-if="isziDian" :tittle="tittle" :code="code" @close="closeZiDain" @itemClick="itemClick"></Dictionary>
</template>
<script>
export const uploadIcon = {
	docx: 'docx',
	doc: 'docx',
	pdf: 'pdf',
	xlsx: 'xlsx',
	xls: 'xlsx'
};
const uploadList = [
	{ name: '聊天记录', value: 'chooseMessageFile' }
	// { name: '本地文件', value: 'chooseFile' }
];
</script>
<script setup>
import Dictionary from './Dictionary.vue';
import { useState } from 'hooks';
import config from '@/config.js';
import _ from 'lodash';
import dayjs from 'dayjs';
import { usersStore } from 'store/users.js';
import Api from 'api';
import files from 'utils/files.js';
const api = new Api
const toast = ref();
const store = usersStore();
const props = defineProps({
	formData: {
		type: Object,
		required: true
	},
	formList: {
		type: Array,
		required: true
	}
});
const dataTimeList = ['开业时间', '停业时间', '营业执照有效期', '出生日期','截止时间']
const datetimePickerRef = ref(null);
const popupITem = ref({});
const ShangChuanItem = ref({});
const isPopup = computed(() => !!props.formList.find(({ type }) => type === 'popup'));
const isShangChaun = computed(() => !!props.formList.find(({ type }) => type === 'upload'));
const isPicker = computed(() => !!props.formList.find(({ type }) => type === 'picker'));
const isDatetime = computed(() => !!props.formList.find(({ type }) => type === 'datetime'));

const uForm = ref(null);
const popupShow = ref(false);
const shangChuanShow = ref(false);
const pickerShow = ref(false);
const datetimeShow = ref(false);
const [popup, setPopupObj] = useState({});
const [pickerObj, setPickerObj] = useState({});
const [datetimeObj, setDatetimeObj] = useState({});
const fileList = ref([]);
const diZhiList = ref([]);
const diZhiItem = ref([]);
const [tiShi, setTiShi] = useState('请选择');
const [isRed, setIsRed] = useState(false);
const deleteShow = ref(false);
const deleteIndex = ref('');
const deleteUrl = ref('');
const shangChuanLinShi = ref({});
const tittle = ref('');
const code = ref('');
const isziDian = ref(false);
const isBianJi = ref(false)
onShow(() => {
	const timeList = props.formList.filter((item) => ['datetime'].includes(item.type));
	timeList.forEach(
		(item) =>
			!!!props.formData[item.prop] &&
			!dataTimeList.includes(item.label) &&
			(props.formData[item.prop] = dayjs().format(item.format))
	);
});
watch(
	() => props.formData,
	(newVal, oldVal) => {
		const upLoad = props.formList.find((item) => ['upload'].includes(item.type));
		upLoad && newVal[upLoad.prop] && (fileList.value = files.formatFileStr(newVal[upLoad.prop]));
	}
);

const changePickerShow = (picker) => {
	setPickerObj(picker);
	setTiShi('请选择');
	if (!store.users?.assress || store.users.assress.length == 0) {
		uni.redirectTo({
			url: '/pages/index/index'
		});
	}
	const data = props.formData[unref(pickerObj).prop]
	if(data){
		
		const arr = data.split('-')
		diZhiItem.value = arr
		let list = store.users.assress
		arr.forEach(item=>{
			list.forEach(i=>{
				item == i.areaName && i.children.length && (list = i.children)
			})
		})
		diZhiList.value = list
		isBianJi.value = !!list[0].children.length
	}else{
		isBianJi.value = false
		diZhiList.value = store.users.assress;
	}
	pickerShow.value = true;
};
const clickTiShi =(item,index)=>{
	isBianJi.value = false
	diZhiItem.value.splice(index,diZhiItem.value.length - index)
	let list = store.users.assress
	 diZhiItem.value.forEach(item=>{
		list.forEach(i=>{
			item == i.areaName && i.children.length && (list = i.children)
		})
	})
	props.formData[unref(pickerObj).prop] = ''
	diZhiList.value = list
}
const diZhiItemClick = (item) => {
	const find = diZhiItem.value.find((i) => i == item.areaName);
	if (find) return;
	const findDiZhi = diZhiList.value.find((i) => i.areaName == item.areaName);
	if(!isBianJi.value){
		if(props.formData[unref(pickerObj).prop] && !!!findDiZhi.children.length)diZhiItem.value.pop()
	}
	diZhiItem.value.push(item.areaName);
	const findChildren = item.children;
	if (findChildren.length)(diZhiList.value = findChildren);
	 else {
		setTiShi('');
		diZhiUp(true);
		props.formData.provinceId = item.id;
	}
};

const diZhiUp = (isZhongDuan) => {
	setTiShi('');
	props.formData[unref(pickerObj).prop] = unref(diZhiItem).join('-');
	uForm.value.validateField(unref(pickerObj).prop);
    isZhongDuan || (props.formData.provinceId = diZhiList.value[0].parentId)
	pickerShow.value = false;
};

const fileCilck = (url) => {
	files.down(url);
};
const deleteFileClick = (item, i, index) => {
	shangChuanLinShi.value = item;
	deleteUrl.value = i;
	deleteIndex.value = index;
	deleteShow.value = true;
};
const confirm = async () => {
	deleteShow.value = false;
	const res = await api.deleteFile({ fileName: files.getFileNameByUrl(deleteUrl.value.url) });
	res && fileList.value.splice(deleteIndex.value, 1);
	props.formData[shangChuanLinShi.value.prop] = unref(fileList).map(({ name, size, url }) => ({ fileName: name, fileSize: size, fileUrl: url }));
};
const clickShangChuan = (item) => {
	shangChuanShow.value = true;
	shangChuanLinShi.value = item;
	enterShangChuan({ name: '聊天记录', value: 'chooseMessageFile' });
};
const enterShangChuan = (item) => {
	ShangChuanItem.value = item;
	shangChuanShow.value = false;
	ShangChuanItem.value = {};
	const extension = ['.doc', '.pdf', '.docx', '.xlsx', '.xls'];
	uni[item.value]({
		count: 1,
		type: 'file',
		extension,
		success(res) {
			const fileName = files.getFileNameByUrl(res.tempFiles[0].name);
			if (unref(fileList).find((item) => item.name == fileName)) {
				toast.value.show({ show: true, message: `${fileName} 已经存在`, type: 'error', position: 'top' });
				return;
			}
			const extensionName = files.getFileExtension(res.tempFiles[0].path);
			if (!extension.includes(extensionName)) {
				toast.value.show({ show: true, message: `不支持 ${extensionName} 格式文件`, type: 'error', position: 'top' });
				return;
			}
			if ((res.tempFiles[0].size / 1024 / 1024).toFixed(2) > 20) {
				toast.value.show({ show: true, message: '文件大小超出20MB，不能上传', type: 'error', position: 'top' });
				return;
			}
			uni.showLoading({
				title: '加载中'
			});
			uni.uploadFile({
				url: `${config.interface}/jeecg-boot/app/upload/uploadFile?bizPath=temp&customBucket=applet&name=${res.tempFiles[0].name}`,
				filePath: res.tempFiles[0].path,
				name: 'file',
				header: {
					'top-token': store.users.token
				},
				success: (res) => {
					uni.hideLoading();
					const obj = JSON.parse(res.data);
					fileList.value.push({ ...obj.result, deleteFile: 'deleteFile' });
					props.formData[shangChuanLinShi.value.prop] = unref(fileList).map(({ name, size, url }) => ({ fileName: name, fileSize: size, fileUrl: url }));
				},
				fail: (err) => {}
			});
		},
		fail: (err) => {
			console.log(err, 'err');
		}
	});
};
const closeZiDain = () => {
	isziDian.value = false;
	tittle.value = '';
	code.value = '';
};
const itemClick = (item) => {
	closeZiDain();
	if(unref(popup).code == 'country'){
		props.formData[unref(popup).prop] = item.id
		props.formData.countryUrl = item.countryUrl
	}else{
		props.formData[unref(popup).prop] = item.value
	}
	props.formList.find((item) => item.prop == unref(popup).prop).columns.push(item);
	uForm.value.validateField(unref(popup).prop);
	// console.log(props.formList.find((item) => item.prop == unref(popup).prop),'item');
};
const changePopupShow = (popup) => {
	setPopupObj(popup, true);
	if (popup.code) {
		isziDian.value = true;
		tittle.value = popup.placeholder;
		code.value = popup.code;
	} else {
		popupITem.value = popup.columns.find((item) => item.value == props.formData[popup.prop]) || {};
		if (popup.disabled) return;
		popupShow.value = true;
	}
};

const changeDatetimeShow = (datetime) => {
	setDatetimeObj(datetime);
	if (datetime.disabled) return;
	datetimeShow.value = true;
};
const pickerConfirm = (e) => {
	if (!e.value.length) return;
	const value = e.value.length == 1 ? e.value[0] : e.value.join(unref(pickerObj).format || '-');
	props.formData[unref(pickerObj).prop] = value;
	pickerShow.value = false;
};

const datetimeConfirm = (e) => {
	if (!e.value) return;
	props.formData[unref(datetimeObj).prop] = dayjs(e.value).format(unref(datetimeObj).format);
	uForm.value.validateField(unref(datetimeObj).prop);
	datetimeShow.value = false;
};

const datetimeClose = () => {
	datetimeShow.value = false;
};
const pickerClose = () => {
	pickerShow.value = false;
};
const enter = (item) => {
	popupITem.value = item;
	props.formData[unref(popup).prop] = unref(popupITem).value;
	uForm.value.validateField(unref(popup).prop);
	popupShow.value = false;
};
watchEffect(() => {
	const formListCopy = _.cloneDeep(props.formList);
	if (!formListCopy) return;
	const rule = formListCopy
		.filter(({ rules }) => rules && rules.length)
		.map(({ prop, rules }) => ({
			[prop]: rules
		}))[0];
	uForm.value && uForm.value?.setRules(rule);
});

const submit = async (cb) => {
	if (!uForm.value) return;
	try {
		const valid = await uForm.value.validate();
		if (valid) cb(reset);
	} catch (e) {
		let timeout;
		if (!timeout) {
			timeout = setTimeout(() => {
				toast.value.show({ show: true, message: '请正确填写必填项', type: 'error', position: 'top' });
				timeout = null;
			}, 20);
		}
		console.warn('校验规则验证失败了呀，别乱填呦~~', e);
	}
};

const reset = () => {
	if (uForm.value) {
		uForm.value.resetFields();
		clear();
	}
};

const clear = () => uForm.value && uForm.value.clearValidate();
const mat = {
	year: '年',
	month: '月',
	day: '日',
	hour: '时',
	minute: '分'
};
const formatter = (type, value) => {
	if (mat[type]) value = value + mat[type];
	return value;
};
onReady(() => {
	datetimePickerRef.value?.setFormatter(formatter);
});
const getPortraitUrl = (item) => {
	uni.chooseImage({
		count: 1, // 默认9，设置图片的选择数量
		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		success(res) {
			uni.showLoading({
				title: '加载中'
			});
			uni.uploadFile({
				url: `${config.interface}/jeecg-boot/app/upload/uploadFile?bizPath=temp&customBucket=applet&name=${res.tempFiles[0].path}`,
				filePath: res.tempFiles[0].path,
				name: 'file',
				header: {
					'top-token': store.users.token
				},
				success: (res) => {
					uni.hideLoading();
					const obj = JSON.parse(res.data);
					props.formData[item.prop] = obj.result.url;
					uForm.value.validateField(item.prop);
				},
				fail: (err) => {
					console.log(err);
					uni.hideLoading();
				}
			});
		},
		fail: function (chooseErr) {
			console.log(chooseErr, 'chooseErr');
		}
	});
};
defineExpose({
	uForm,
	submit,
	reset,
	clear
});
</script>

<style lang="scss" scoped>
.kuang {
	min-height: 1.4rem;
	display: block;
	text-align: right;
	font-size: 30rpx;
	font-family: UICTFontTextStyleBody;
}
.you {
	color: #303133;
}
.wu {
	color: #888888;
}
.diZhi {
	height: 67vh;
	padding: 32rpx;
	.con {
		overflow: auto;
		height: 62vh;
	}
	.con_item {
		margin: 28rpx 0;
		color: #222222;
	}
	.con_item:last-of-type {
		margin-bottom: 100rpx;
	}
	.dizhiItem {
		display: flex;
		margin: 28rpx 0;
		& > view {
			margin-right: 32rpx;
		}
		.xuanZe {
			color: #222222;
		}
		.tiShi {
			color: #458cff;
		}
	}
	.top {
		.zhanwei {
			width: 48rpx;
		}
		.titt {
			font-size: 36rpx;
			color: #222222;
			font-weight: 700;
		}
	}
}
.form {
	background-color: #ffffff;
	padding-bottom: 8rpx;
}
.shangchaun {
	margin-top: 16rpx;
	.tu {
		display: flex;
		align-items: center;
		border-radius: 20rpx;
		border: 2rpx solid #f3f3f3;
		margin-bottom: 16rpx;
	}
	.img {
		width: 48rpx;
		height: 48rpx;
	}
	.imgDa {
		width: 132rpx;
		height: 132rpx;
	}
	.cen {
		width: 450rpx;
		margin-left: 32rpx;
		.name {
			color: #222222;
			margin-bottom: 16rpx;
			overflow: hidden;
			-webkit-line-clamp: 1;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-box-orient: vertical;
		}
		.daXiao {
			font-size: 24rpx;
		}
	}

	.fileAdd {
		display: flex;
		align-items: center;
		margin-top: 32rpx;
		.right {
			margin-left: 30rpx;
			view {
				font-size: 24rpx;
				font-style: normal;
			}
			view:first-child {
				margin-bottom: 16rpx;
			}
		}
	}
}
</style>
